<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
use wechat\WxPay;

/**
 * 订单接口
 */
class Order extends Api
{

    protected $noNeedLogin = ['notify'];
    protected $noNeedRight = ['*'];
    protected $goods;


    // protected $limitFields = 'name';
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\Order();
        $this->goods = new \app\common\model\Goods();
    }


    /**
     * 提交订单
     */
    public function add()
    {
        $params = $this->request->post();
        $params['user_id'] = $this->auth->id;
        $userinfo = Db::name('user')->where(['id' => $this->auth->id])->find();

        //活动订单
        if ($params['order_prom_type'] > 0 && $params['order_prom_id'] > 0) {

            $orderLogic = new \app\common\logic\OrderLogic();
            $isCanAddOrder = $orderLogic->PromIsCanAddOrder($params['order_prom_type'], $params['goods_id'], $params['order_prom_id'], $params['num']);
            if ($isCanAddOrder['code'] == 0) {
                $this->error($isCanAddOrder['msg']);
            }

        }

        $res = $this->model->addOrder($params);
        if ($res['code'] == 1) {
            $goods = Db::name('goods')->where(['id' => $res['data']['goods_id']])->find();

            if ($res['data']['type'] == '2') {
                //群发多人抢
                $data = [
//                    'order_id' => $res['data']['order_id'],
                    'type' => $res['data']['type'],
                    'order_sn' => $res['data']['master_order_sn'],
                    'goods_name' => $goods['name'],
                    'total_amount' => $res['data']['total_amount'],
                    'openid' => $userinfo['openid']
                ];
            } elseif ($res['data']['type'] == '1') {
                //送一人

                $data = [
                    'type' => $res['data']['type'],
                    'order_sn' => $res['data']['order_sn'],
                    'goods_name' => $goods['name'],
                    'total_amount' => $res['data']['total_amount'],
                    'openid' => $userinfo['openid']
                ];
            } else {
                //自己买
                $data = [
//                    'order_id' => $res['data']['order_id'],
                    'type' => $res['data']['type'],
                    'order_sn' => $res['data']['order_sn'],
                    'goods_name' => $goods['name'],
                    'total_amount' => $res['data']['total_amount'],
                    'openid' => $userinfo['openid']
                ];

            }

            //当拼团订单下单成功后
            $order = $this->model->get($res['data']['order_id']);
            if ($order['order_prom_type'] == 2) {
                $order_id = $res['data']['order_id'];
                $teamOrderLogic = new \app\common\logic\TeamOrderLogic();
                $order = $this->model->get($order_id);
                $teamOrderLogic->setUserId($this->auth->id);
                $goods = $this->goods->get($order->goods_id);
                $teamOrderLogic->setGoods($goods);
                $teamM = new \app\common\model\TeamActivity();
                $team = $teamM->get($order->order_prom_id);
                $teamOrderLogic->setTeam($team);
                $teamOrderLogic->setOrder($order);

                //判断是团长下单，还是团员下单
                if ($params['user_prom_id']) {
                    //团员下单

                    //判断是否参与过此团
                    $isHasTeamFollow = $teamOrderLogic->isHasTeamFollow($params['user_prom_id'],$this->auth->id);
                    if(!$isHasTeamFollow){
                        //未参与过
                        $teamFoundM = new \app\common\model\TeamFound();
                        $teamFound = $teamFoundM->get($params['user_prom_id']);
                        $teamOrderLogic->setTeamFound($teamFound);

                        $teamOrderData = $teamOrderLogic->afterAddOrder();
                        if ($teamOrderData['code'] == 1) {
                            $data['found_id'] = $teamOrderData['data']['found_id'];
                        } else {
                            $this->error($teamOrderData['msg']);
                        }

                    }else{
                        //参与过
                        $this->error('您已经参与过此团, 不能重复拼团');

                    }

                }else{
                    //团长下单
                    $teamOrderData = $teamOrderLogic->afterAddOrder();
                    if ($teamOrderData['code'] == 1) {
                        $data['found_id'] = $teamOrderData['data']['found_id'];
                    } else {
                        $this->error($teamOrderData['msg']);
                    }

                }


            }



            $this->success($res['msg'], $data);
        } else {
            $this->error($res['msg']);
        }


    }

    //调起小程序支付
    public function getpay()
    {

        $fee = $this->request->request('total_amount');
        $details = $this->request->request('details');
        $openid = $this->request->request('openid');
        $order_sn = $this->request->request('order_sn');

        $wxpay = new WxPay;
        $data = $wxpay->pay($openid, $fee, $details, $order_sn);
        echo json_encode($data);
    }

    //异步通知
    public function notify()
    {
        $xmlData = file_get_contents('php://input');

        libxml_disable_entity_loader(true);
        $data = json_decode(json_encode(simplexml_load_string($xmlData, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        file_put_contents('./log/notify.php', json_encode($data).PHP_EOL, FILE_APPEND);


        ksort($data);
        $buff = '';
        foreach ($data as $k => $v) {
            if ($k != 'sign') {
                $buff .= $k . '=' . $v . '&';
            }
        }
        $stringSignTemp = $buff . 'key=MANQUbuA6N9JpbiDWBLYEnMX7ZzpozPZ';//key为证书密钥,商户key
        $sign = strtoupper(md5($stringSignTemp));
        //判断算出的签名和通知信息的签名是否一致
        if ($sign == $data['sign']) {
            //修改订单状态
            // $this->updateOrderStatus($data['out_trade_no']);
            update_pay_status($data['out_trade_no']);

            //处理完成之后，告诉微信成功结果
            echo '<xml>
                      <return_code><![CDATA[SUCCESS]]></return_code>
                      <return_msg><![CDATA[OK]]></return_msg>
                  </xml>';
            exit();
        } else {
            file_put_contents('./log/notify.php', 'notify签名错误'.PHP_EOL, FILE_APPEND);

        }
    }


    /**
     * 我的订单列表
     */
    public function myorder()
    {
        //0 = 全部订单，1=待支付，2=待发货，3=待收货，4=交易完成，5=已退款
        $orderType = $this->request->request('order_type', 0);
        if ($orderType == 1) {
            $typeWhere = ['pay_status' => 0,'order_status' => 0];

        } elseif ($orderType == 2) {
            $typeWhere = ['pay_status' => 1, 'order_status' => 1, 'shipping_status' =>0];

        } elseif ($orderType == 3) {
            $typeWhere = ['pay_status' => 1, 'order_status' => 1,'shipping_status' => 1];

        } elseif ($orderType == 4) {
            $typeWhere = ['pay_status' => 1, 'order_status' => 2];

        } elseif ($orderType == 5) {
            $typeWhere = ['pay_status' => 3];

        } else {
            //全部
            $typeWhere = ['order_status' => ['<>',3]];
        }

        $this->dataLimit = true;
        list($where, $sort, $order, $offset, $limit, $field) = $this->buildparams();

        $total = $this->model
            ->where($where)
            ->where($typeWhere)
            ->where(function ($query) {
                $query->where(['deleted' => 0, 'order_status' => ['<>', 5]]);
            })
            ->order($sort, $order)
            ->count();

        $list = $this->model
            ->with('goods')
            ->field($field)
            ->where($where)
            ->where($typeWhere)
            ->where(function ($query) {
                $query->where(['deleted' => 0, 'order_status' => ['<>', 5]]);
            })
            ->order($sort, $order)
            ->limit($offset, $limit)
            ->select();

        $result = array("total" => $total, "rows" => $list);


        $this->success('', $result);


    }

    /**
     * 取消订单
     */
    public function cancelOrder()
    {
        $order_id = $this->request->request('order_id');
        $order = $this->model->get($order_id);
        $orderLogic = new \app\common\logic\OrderLogic();
        $orderLogic->setOrder($order);
        $res = $orderLogic->cancelOrder();
        if ($res['code'] == 1) {
            $this->success($res['msg']);
        } else {
            $this->error($res['msg']);
        }
    }

    /**
     * 去付款
     */
    public function dopay()
    {
        $order_id = $this->request->request('order_id');
        $order = $this->model->get($order_id);
        $order->goods;
        $order->user;
//        dump($order->toArray());exit;
        if (empty($order)) {

            $this->error('订单不存在');
        }

        if ($order['pay_status'] > 0 || $order['order_status'] > 0) {

            $this->error('支付状态或订单状态不允许');
        }

        $data = [
            'total_amount' => $order['total_amount'],
            'details' => $order->goods['name'],
            'openid' => $order->user['openid'],
            'order_sn' => $order['order_sn']
        ];

        $this->success('', $data);
    }

    /**
     * 详情
     */
    public function detail($ids = NULL)
    {
        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        $row->goods;
        $row->address;
        $this->success('', $row);
    }

    /**
     * 删除订单
     */
    public function delOrder($ids = null)
    {
        $order = $this->model->get($ids);
        if (empty($order)) {
            $this->error('订单不存在');
        }

        $order->deleted = 1;
        $res = $order->save();
        if ($res !== false) {
            $this->success('订单删除成功');
        } else {
            $this->error('订单删除失败');
        }
    }


    public function shippingInfo($ids = null){
        $order = $this->model->get($ids);
        if (empty($order)) {
            $this->error('订单不存在');
        }

        $this->success('',['shipping_name' => $order['shipping_name'], 'shipping_code' => $order['shipping_code']]);

    }


    /**
     * 模拟订单支付 -- 上线删除
     */
    public function moni()
    {
        $order_sn = $this->request->request('order_sn');
        update_pay_status($order_sn);
    }


}